package com.plum.admin.modules.social.service.impl;

import cn.hutool.core.util.URLUtil;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.plum.admin.common.constant.Constant;
import com.plum.admin.modules.social.entity.SysSocial;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2021/9/16 9:17
 */
@Service
@Slf4j
public class AlipayLoginService implements InitializingBean {
    /**
     * 支付宝appId
     */
    @Value("${social.alipay.appId}")
    private String appId;


    /**
     * 私钥
     */
    private static final String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCHsDZwcQ7nD2zv5/I9MVuTsKAx6REnJ14A4aCYjNRLa7otgayRvxxR47iGHz7qnlCSyEjJN5B5M26qOkAyyfX3sp6VM8wNoaYI5p+HccFtWhZuV45v4JoPWQ73J9rt6z8xq5HWwvm83t4oxemLyyu/7Vi/sAGn9IgRNy9qI82Op7e5MG91eqBgMS6AT40q+lWcBgF24Z0c1CedBurT7Kb9qd/H1gKfQaItqokVCiJB97jqObG8DdOkjzsIKko0BrufaF5tJM1gMVwc+Bx67+pZled14W/Clkidb2tcjXhqe+PWiCM9WqMGyx0YpmGDBnNNjOx51wQlaFHTQKU3WAF7AgMBAAECggEABXuBN5nZ2EwvQqJEj2RnJtiEIIAiSUq16aM0MfW+vi1kIGKU7m6iXkytL/4jNKeg6c1d44NzOvJxDj+8SFEQtylobu7g18woQUPQPlDCWADD10GCZ9LTZrtad3IMzoAq1X7xLZRDMvZuU4droFJdOiwE4fnilz6yIL/yEn/P1muxVsGQaN2C3oYJ1vuSlFt40/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AQEFAAOCAQ8AMIIBCgKCAQEA1Yu6Y/DDOKnLGMlsy5j/dJ1FEmOcTemwZLu6MBaWL/6Lr7Qd2t1TaNWU7unyq5cRi4JgLUrGv7F+CFC6DvyY71cUNcuTAGkd37YVxQ3tprPaOYoK/030IFSEtFqZ2rJZ5FSB2tl18lK65qkvKv40dYY8mVFUq4lt8mOegfXMofwEV0yHd4xem/eEy5SfFS4rXsShYRJ0RNalNBV6u0VmYzfvI2QNxlWRuIdJtnren7gjsLEOpe4GatMTqmhydn+iB3qwOdpf9Bfizv7YS1lNDanAy9JvucdbE5AbAHL8GCEZIKq98ZQyLUz9zK+KLL0WZuKOVHbUVj5/aqdZf9/CEQIDAQAB";
    /**
     * 支付宝认证地址
     */
    private static final String AUTHORIZE_URL="https://openauth.alipay.com/oauth2/publicAppAuthorize.htm";

    /**
     * 获取token及openId
     */
    private static final String ACCESS_TOKEN_URL="https://openapi.alipay.com/gateway.do";
    /**Alipay客户端*/
    private AlipayClient alipayClient;

    /**
     * 生成支付宝认证链接
     * @param callbackUrl
     * @return
     */
    public String getAuthorizeUrl(String callbackUrl){
        StringBuilder url=new StringBuilder();
        String state=String.valueOf(System.currentTimeMillis());
        url.append(AUTHORIZE_URL)
                .append("?app_id=").append(appId)
                .append("&scope=auth_user,auth_base&redirect_uri=")
                .append(URLUtil.encode(callbackUrl,"UTF-8"))
                .append("&state=")
                .append(state);
        return url.toString();
    }

    public String getAccessToken(String authCode){
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setCode(authCode);
        request.setGrantType("authorization_code");
        try {
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
            return oauthTokenResponse.getAccessToken();
        } catch (Exception e) {
            log.error("使用authCode获取信息失败！", e);
            return null;
        }
    }
    public SysSocial getUserInfo(String token){
        AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest ();
        SysSocial social=null;
        try {
            AlipayUserInfoShareResponse response =  alipayClient.execute(request, token);
            if (response.isSuccess()) {
                social=new SysSocial();
                social.setAvatar(response.getAvatar());
                social.setNickName(response.getNickName());
                social.setOpenId(token);
                social.setPlatform(Constant.SOCIAL_TYPE_ALIPAY);
                return social;
            }
        } catch (Exception e) {
            log.error("根据 access_token获取用户信息抛出异常！", e);
            return null;
        }
        return null;
    }
    @Override
    public void afterPropertiesSet() {
        alipayClient=new DefaultAlipayClient(ACCESS_TOKEN_URL, appId, APP_PRIVATE_KEY, "json", "UTF-8", ALIPAY_PUBLIC_KEY, "RSA2");
    }
}
